package com.itheima.web.manager;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.crypto.SecureUtil;
import com.itheima.domain.db.Admin;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;

@Service
public class AdminManager {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private AdminService adminService;

    //生成验证码
    public LineCaptcha genVerification(String uuid) {
        //1. 创建验证码
        LineCaptcha lineCaptcha = new LineCaptcha(300, 100);
        String code = lineCaptcha.getCode();
        System.out.println("验证码:" + code);

        //2. 保存到redis
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_CODE + uuid, code, Duration.ofMinutes(5));

        //3. 返回验证码
        return lineCaptcha;
    }

    //用户登录
    public String login(String username, String password, String verificationCode, String uuid) {
        //1. 检验验证码,如果失败,直接返回错误
        String codeFromRedis = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_CODE + uuid);
        if (!StringUtils.equals(verificationCode, codeFromRedis)) {
            throw new BusinessException("验证码错误");
        }

        //2. 校验用户名,如果失败,直接返回错误
        Admin admin = adminService.findByUserName(username);
        if (admin == null) {
            throw new BusinessException("用户名不存在");
        }

        //3. 校验密码,如果失败,直接返回错误
        String passwordWithMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(passwordWithMd5, admin.getPassword())) {
            throw new BusinessException("密码错误");
        }

        //模拟的未知性异常
        //int i = 1 / 0;


        //4. 说明登录成功
        //4-1. 删除redis中的验证码
        stringRedisTemplate.delete(ConstantUtil.ADMIN_CODE + uuid);

        //4-2. 创建token,保存在redis中,再返回
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", admin.getId());
        map.put("username", admin.getUsername());
        String token = JwtUtil.createToken(map);

        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, "1", Duration.ofHours(1));

        return token;
    }

    public Admin findByUsername(String username) {
        return adminService.findByUserName(username);
    }

    //用户退出
    public void logout(String token) {
        //本质上就是删除掉redis中当前用户的token
        stringRedisTemplate.delete(ConstantUtil.ADMIN_TOKEN + token);
    }
}
